<template>
  <div class="camera-algorithm-binding">
    <div class="binding-header">
      <h3>摄像头算法绑定管理</h3>
      <div class="header-actions">
        <el-button type="primary" :icon="Plus" @click="showBindingDialog = true">
          添加绑定
        </el-button>
        <el-button :icon="Refresh" @click="loadBindings">刷新</el-button>
      </div>
    </div>

    <!-- 统计信息 -->
    <div class="binding-stats">
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-number">{{ bindings.length }}</div>
            <div class="stat-label">绑定摄像头</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-number">{{ totalAlgorithms }}</div>
            <div class="stat-label">绑定算法</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-number">{{ activeAlgorithms }}</div>
            <div class="stat-label">启用算法</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-number">{{ Object.keys(AI_SERVICES_WITH_ALGORITHMS).length }}</div>
            <div class="stat-label">AI服务</div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 绑定列表 -->
    <div class="bindings-list">
      <el-table :data="bindings" v-loading="loading" stripe>
        <el-table-column prop="camera_name" label="摄像头" width="200">
          <template #default="{ row }">
            <div class="camera-info">
              <el-icon><VideoCamera /></el-icon>
              <span>{{ row.camera_name }}</span>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="绑定算法" min-width="400">
          <template #default="{ row }">
            <div class="algorithms-list">
              <el-tag 
                v-for="algorithm in row.algorithms" 
                :key="algorithm.algorithm_id"
                :type="algorithm.enabled ? 'success' : 'info'"
                size="small"
                class="algorithm-tag"
              >
                {{ getAlgorithmDisplayName(algorithm.algorithm_id) }}
                <span class="priority">P{{ algorithm.priority }}</span>
              </el-tag>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="updated_at" label="更新时间" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.updated_at) }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button size="small" @click="editBinding(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteBinding(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 添加/编辑绑定对话框 -->
    <el-dialog
      v-model="showBindingDialog"
      :title="editingBinding ? '编辑算法绑定' : '添加算法绑定'"
      width="1000px"
      @close="resetBindingForm"
    >
      <el-form :model="bindingForm" :rules="bindingRules" ref="bindingFormRef" label-width="120px">
        <el-form-item label="摄像头" prop="camera_id">
          <el-select v-model="bindingForm.camera_id" placeholder="请选择摄像头" style="width: 100%">
            <el-option 
              v-for="camera in cameras" 
              :key="camera.id"
              :label="camera.name" 
              :value="camera.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="算法配置">

          <!-- 按服务分组的算法选择 -->
          <div class="services-selection">
            <el-tabs v-model="activeServiceTab" type="border-card">
              <el-tab-pane 
                v-for="(serviceInfo, serviceId) in AI_SERVICES_WITH_ALGORITHMS" 
                :key="serviceId"
                :label="serviceInfo.name" 
                :name="serviceId"
              >
                <div class="service-algorithms">
                  <div class="service-description">
                    <p>{{ getServiceDescription(serviceId) }}</p>
                  </div>
                  
                  <div class="algorithms-grid">
                    <div 
                      v-for="(algorithmName, algorithmType) in serviceInfo.algorithms"
                      :key="algorithmType"
                      class="algorithm-option"
                      :class="{ 
                        'selected': isAlgorithmSelected(serviceId, algorithmType),
                        'enabled': getSelectedAlgorithm(serviceId, algorithmType)?.enabled 
                      }"
                      @click="toggleAlgorithm(serviceId, algorithmType, algorithmName)"
                    >
                      <div class="algorithm-card">
                        <div class="algorithm-header">
                          <el-checkbox 
                            :model-value="isAlgorithmSelected(serviceId, algorithmType)"
                            @change="toggleAlgorithm(serviceId, algorithmType, algorithmName)"
                          />
                          <h4>{{ algorithmName }}</h4>
                        </div>
                        
                        <div class="algorithm-info">
                          <p class="algorithm-id">{{ algorithmType }}</p>
                          <p class="algorithm-desc">{{ getAlgorithmDescription(serviceId, algorithmType) }}</p>
                        </div>
                        
                        <!-- 算法配置 -->
                        <div v-if="isAlgorithmSelected(serviceId, algorithmType)" class="algorithm-config">
                          <el-divider />
                          <el-row :gutter="12">
                            <el-col :span="8">
                              <el-form-item label="优先级" size="small">
                                <el-input-number 
                                  v-model="getSelectedAlgorithm(serviceId, algorithmType).priority"
                                  :min="1" 
                                  :max="10"
                                  size="small"
                                  style="width: 100%"
                                />
                              </el-form-item>
                            </el-col>
                            <el-col :span="8">
                              <el-form-item label="置信度" size="small">
                                <el-input-number 
                                  v-model="getSelectedAlgorithm(serviceId, algorithmType).config.confidence_threshold"
                                  :min="0.1" 
                                  :max="1"
                                  :step="0.1"
                                  size="small"
                                  style="width: 100%"
                                />
                              </el-form-item>
                            </el-col>
                            <el-col :span="8">
                              <el-form-item label="间隔(秒)" size="small">
                                <el-input-number 
                                  v-model="getSelectedAlgorithm(serviceId, algorithmType).config.detection_interval"
                                  :min="1" 
                                  :max="60"
                                  size="small"
                                  style="width: 100%"
                                />
                              </el-form-item>
                            </el-col>
                          </el-row>
                          
                          <el-form-item label="启用算法" size="small">
                            <el-switch 
                              v-model="getSelectedAlgorithm(serviceId, algorithmType).enabled"
                              active-text="启用"
                              inactive-text="禁用"
                            />
                          </el-form-item>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </el-tab-pane>
            </el-tabs>
          </div>

          <!-- 已选择的算法摘要 -->
          <div v-if="bindingForm.algorithms.length > 0" class="selected-summary">
            <el-divider content-position="left">已选择的算法 ({{ bindingForm.algorithms.length }})</el-divider>
            <div class="summary-list">
              <el-tag 
                v-for="algorithm in bindingForm.algorithms"
                :key="algorithm.algorithm_id"
                :type="algorithm.enabled ? 'success' : 'info'"
                size="small"
                closable
                @close="removeAlgorithmById(algorithm.algorithm_id)"
              >
                {{ algorithm.algorithm_name }} (P{{ algorithm.priority }})
              </el-tag>
            </div>
          </div>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <div class="footer-info">
            已选择 {{ bindingForm.algorithms.length }} 个算法
          </div>
          <div class="footer-actions">
            <el-button @click="showBindingDialog = false">取消</el-button>
            <el-button type="primary" @click="saveBinding" :loading="saving">
              {{ editingBinding ? '更新绑定' : '创建绑定' }}
            </el-button>
          </div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Refresh, VideoCamera, Delete } from '@element-plus/icons-vue'
import { aiAlgorithmApi, AI_SERVICES } from '@/api/ai-algorithm'
import { useCameraStore } from '@/store/modules/camera'

// 使用camera store
const cameraStore = useCameraStore()

// 六大AI服务及其具体算法
const AI_SERVICES_WITH_ALGORITHMS = {
  'campus_behavior_monitoring': {
    'name': '校园行为监控',
    'algorithms': {
      'person_detection': '人员检测算法',
      'behavior_analysis': '行为分析算法',
      'abnormal_behavior': '异常行为识别',
      'crowd_gathering': '人群聚集检测',
      'violence_detection': '暴力行为检测'
    }
  },
  'campus_crowd_safety': {
    'name': '校园人群安全',
    'algorithms': {
      'crowd_density': '人群密度分析',
      'crowd_flow': '人流量统计',
      'evacuation_route': '疏散路径规划',
      'safety_monitoring': '安全监控算法',
      'emergency_detection': '紧急情况检测'
    }
  },
  'campus_energy_management': {
    'name': '校园能源管理',
    'algorithms': {
      'lighting_control': '照明控制算法',
      'occupancy_detection': '空间占用检测',
      'energy_optimization': '能耗优化算法',
      'equipment_monitoring': '设备监控算法',
      'power_analysis': '电力分析算法'
    }
  },
  'campus_environment_hygiene': {
    'name': '校园环境卫生',
    'algorithms': {
      'waste_detection': '垃圾检测算法',
      'cleanliness_assessment': '清洁度评估',
      'hygiene_monitoring': '卫生监控算法',
      'cleaning_efficiency': '清洁效率分析',
      'maintenance_alert': '维护提醒算法'
    }
  },
  'intelligent_classroom_quality': {
    'name': '智能课堂质量',
    'algorithms': {
      'attention_analysis': '注意力分析',
      'participation_tracking': '参与度跟踪',
      'learning_assessment': '学习效果评估',
      'classroom_environment': '课堂环境监测',
      'interaction_analysis': '互动分析算法'
    }
  },
  'teaching_quality_assessment': {
    'name': '教学质量评估',
    'algorithms': {
      'teacher_behavior': '教师行为分析',
      'teaching_style': '教学风格识别',
      'student_engagement': '学生参与度分析',
      'content_delivery': '内容传达效果',
      'feedback_analysis': '反馈分析算法'
    }
  }
}

// 响应式数据
const bindings = ref([])
const loading = ref(false)
const saving = ref(false)
const showBindingDialog = ref(false)
const editingBinding = ref(null)
const bindingFormRef = ref()
const activeServiceTab = ref('campus_behavior_monitoring')

// 从camera store获取摄像头列表
const cameras = computed(() => {
  return cameraStore.cameras.map(camera => ({
    id: camera.id,
    name: camera.name,
    location: camera.location,
    status: camera.status
  }))
})

// 统计信息
const totalAlgorithms = computed(() => {
  return bindings.value.reduce((sum, binding) => sum + binding.algorithms.length, 0)
})

const activeAlgorithms = computed(() => {
  return bindings.value.reduce((sum, binding) => {
    return sum + binding.algorithms.filter(alg => alg.enabled).length
  }, 0)
})

// 表单数据
const bindingForm = ref({
  camera_id: '',
  camera_name: '',
  algorithms: []
})

// 表单验证规则
const bindingRules = {
  camera_id: [{ required: true, message: '请选择摄像头', trigger: 'change' }]
}

// 工具方法
const getServiceDescription = (serviceId) => {
  const descriptions = {
    'campus_behavior_monitoring': '智能识别和分析校园内人员行为，确保校园安全',
    'campus_crowd_safety': '监控人群密度和流动，预防安全事故发生',
    'campus_energy_management': '优化校园能源使用，实现绿色智能管理',
    'campus_environment_hygiene': '监测校园环境质量，维护清洁卫生标准',
    'intelligent_classroom_quality': '分析课堂教学质量，提升教育效果',
    'teaching_quality_assessment': '评估教师教学水平，优化教学方法'
  }
  return descriptions[serviceId] || '智能AI服务'
}

const getAlgorithmDescription = (serviceId, algorithmType) => {
  const descriptions = {
    'campus_behavior_monitoring': {
      'person_detection': '检测和识别校园内的人员',
      'behavior_analysis': '分析人员行为模式',
      'abnormal_behavior': '识别异常或可疑行为',
      'crowd_gathering': '检测人群聚集情况',
      'violence_detection': '检测暴力行为'
    },
    'campus_crowd_safety': {
      'crowd_density': '分析区域人群密度',
      'crowd_flow': '统计人流量和方向',
      'evacuation_route': '规划最优疏散路径',
      'safety_monitoring': '实时安全监控',
      'emergency_detection': '检测紧急情况'
    },
    'campus_energy_management': {
      'lighting_control': '智能照明控制',
      'occupancy_detection': '检测空间占用情况',
      'energy_optimization': '优化能源使用',
      'equipment_monitoring': '监控设备运行状态',
      'power_analysis': '分析电力使用情况'
    },
    'campus_environment_hygiene': {
      'waste_detection': '检测垃圾和废物',
      'cleanliness_assessment': '评估清洁度',
      'hygiene_monitoring': '监控卫生状况',
      'cleaning_efficiency': '分析清洁效率',
      'maintenance_alert': '维护提醒'
    },
    'intelligent_classroom_quality': {
      'attention_analysis': '分析学生注意力',
      'participation_tracking': '跟踪学生参与度',
      'learning_assessment': '评估学习效果',
      'classroom_environment': '监测课堂环境',
      'interaction_analysis': '分析师生互动'
    },
    'teaching_quality_assessment': {
      'teacher_behavior': '分析教师行为',
      'teaching_style': '识别教学风格',
      'student_engagement': '分析学生参与度',
      'content_delivery': '评估内容传达效果',
      'feedback_analysis': '分析反馈信息'
    }
  }
  return descriptions[serviceId]?.[algorithmType] || '专业AI算法'
}

// 算法选择相关方法
const isAlgorithmSelected = (serviceId, algorithmType) => {
  const algorithmId = `${serviceId}_${algorithmType}`
  return bindingForm.value.algorithms.some(alg => alg.algorithm_id === algorithmId)
}

const getSelectedAlgorithm = (serviceId, algorithmType) => {
  const algorithmId = `${serviceId}_${algorithmType}`
  return bindingForm.value.algorithms.find(alg => alg.algorithm_id === algorithmId)
}

const toggleAlgorithm = (serviceId, algorithmType, algorithmName) => {
  const algorithmId = `${serviceId}_${algorithmType}`
  const existingIndex = bindingForm.value.algorithms.findIndex(alg => alg.algorithm_id === algorithmId)
  
  if (existingIndex !== -1) {
    // 移除算法
    bindingForm.value.algorithms.splice(existingIndex, 1)
  } else {
    // 添加算法
    bindingForm.value.algorithms.push({
      algorithm_id: algorithmId,
      algorithm_name: algorithmName,
      service_id: serviceId,
      algorithm_type: algorithmType,
      enabled: true,
      priority: bindingForm.value.algorithms.length + 1,
      config: {
        confidence_threshold: 0.7,
        detection_interval: 5,
        max_detections: 10
      }
    })
  }
  
  // 重新调整优先级
  bindingForm.value.algorithms.forEach((alg, idx) => {
    alg.priority = idx + 1
  })
}

const removeAlgorithmById = (algorithmId) => {
  const index = bindingForm.value.algorithms.findIndex(alg => alg.algorithm_id === algorithmId)
  if (index !== -1) {
    bindingForm.value.algorithms.splice(index, 1)
    // 重新调整优先级
    bindingForm.value.algorithms.forEach((alg, idx) => {
      alg.priority = idx + 1
    })
  }
}

// 获取算法显示名称
const getAlgorithmDisplayName = (algorithmId) => {
  // 解析算法ID
  const parts = algorithmId.split('_')
  if (parts.length >= 2) {
    const serviceId = parts.slice(0, -1).join('_')
    const algorithmType = parts[parts.length - 1]
    
    const serviceInfo = AI_SERVICES_WITH_ALGORITHMS[serviceId]
    if (serviceInfo && serviceInfo.algorithms[algorithmType]) {
      return serviceInfo.algorithms[algorithmType]
    }
  }
  
  // 如果无法解析，返回原ID
  return algorithmId
}

// 加载数据
const loadBindings = async () => {
  loading.value = true
  console.log('🔄 开始加载摄像头绑定数据...')
  
  try {
    const response = await aiAlgorithmApi.getCameraBindings()
    console.log('📡 API响应:', response)
    
    if (response && response.code === 200) {
      const bindingData = response.data || []
      bindings.value = Array.isArray(bindingData) ? bindingData : []
      console.log(`✅ 成功加载 ${bindings.value.length} 个摄像头绑定`)
      
      if (bindings.value.length === 0) {
        console.log('ℹ️ 数据库中暂无摄像头绑定数据')
        ElMessage.info('暂无摄像头绑定数据，请添加新的绑定')
      }
    } else {
      console.warn('⚠️ API返回非成功状态:', response)
      ElMessage.warning(`获取绑定数据失败: ${response?.msg || '未知错误'}`)
      bindings.value = []
    }
  } catch (err) {
    console.error('❌ 加载绑定失败:', err)
    
    // 显示具体的错误信息
    if (err.response) {
      const status = err.response.status
      const message = err.response.data?.msg || err.message
      ElMessage.error(`API调用失败 (${status}): ${message}`)
    } else if (err.request) {
      ElMessage.error('无法连接到后端服务，请检查网络连接和服务状态')
    } else {
      ElMessage.error(`请求配置错误: ${err.message}`)
    }
    
    // 设置为空数组，不使用模拟数据
    bindings.value = []
    
    console.log('💡 请检查:')
    console.log('   1. 后端服务是否运行在 http://localhost:8001')
    console.log('   2. API路由是否正确注册')
    console.log('   3. 前端代理配置是否正确')
    console.log('   4. 浏览器网络请求是否成功')
  } finally {
    loading.value = false
  }
}

// 生成模拟绑定数据
const generateMockBindings = () => {
  const mockBindings = []
  const cameraList = cameraStore.cameras.slice(0, 3) // 取前3个摄像头
  
  cameraList.forEach((camera, index) => {
    const serviceKeys = Object.keys(AI_SERVICES_WITH_ALGORITHMS)
    const selectedService = serviceKeys[index % serviceKeys.length]
    const serviceInfo = AI_SERVICES_WITH_ALGORITHMS[selectedService]
    
    // 为每个摄像头选择2-3个算法
    const algorithmTypes = Object.keys(serviceInfo.algorithms)
    const selectedAlgorithms = algorithmTypes.slice(0, 2 + (index % 2))
    
    mockBindings.push({
      id: `binding_${camera.id}`,
      camera_id: camera.id,
      camera_name: camera.name,
      algorithms: selectedAlgorithms.map((algorithmType, algIndex) => ({
        algorithm_id: `${selectedService}_${algorithmType}`,
        algorithm_name: serviceInfo.algorithms[algorithmType],
        service_id: selectedService,
        algorithm_type: algorithmType,
        enabled: Math.random() > 0.3,
        priority: algIndex + 1,
        config: {
          confidence_threshold: Math.round((Math.random() * 0.3 + 0.6) * 10) / 10,
          detection_interval: Math.floor(Math.random() * 10) + 3,
          max_detections: Math.floor(Math.random() * 5) + 5
        }
      })),
      created_at: new Date(Date.now() - Math.random() * 7 * 24 * 60 * 60 * 1000).toISOString(),
      updated_at: new Date(Date.now() - Math.random() * 24 * 60 * 60 * 1000).toISOString()
    })
  })
  
  return mockBindings
}

// 编辑绑定
const editBinding = (binding) => {
  editingBinding.value = binding
  bindingForm.value = {
    camera_id: binding.camera_id,
    camera_name: binding.camera_name,
    algorithms: JSON.parse(JSON.stringify(binding.algorithms))
  }
  showBindingDialog.value = true
}

// 删除绑定
const deleteBinding = async (binding) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除摄像头 "${binding.camera_name}" 的算法绑定吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    try {
      const response = await aiAlgorithmApi.deleteCameraBinding(binding.camera_id)
      if (response.code === 200) {
        ElMessage.success('删除成功')
      } else {
        throw new Error(response.msg || '删除失败')
      }
    } catch (apiError) {
      console.error('API删除失败:', apiError)
      ElMessage.warning('后端服务暂不可用，已从本地缓存中删除')
      
      // 从本地数据中删除
      const index = bindings.value.findIndex(b => b.camera_id === binding.camera_id)
      if (index !== -1) {
        bindings.value.splice(index, 1)
      }
    }
    
    await loadBindings()
  } catch (err) {
    if (err !== 'cancel') {
      console.error('删除绑定失败:', err)
      ElMessage.error('删除失败')
    }
  }
}

// 保存绑定
const saveBinding = async () => {
  if (!bindingFormRef.value) return
  
  try {
    await bindingFormRef.value.validate()
    
    if (bindingForm.value.algorithms.length === 0) {
      ElMessage.warning('请至少添加一个算法')
      return
    }
    
    // 验证算法配置
    const invalidAlgorithms = bindingForm.value.algorithms.filter(alg => !alg.algorithm_id)
    if (invalidAlgorithms.length > 0) {
      ElMessage.warning('请为所有算法选择具体的算法')
      return
    }
    
    saving.value = true
    
    // 设置摄像头名称
    const camera = cameras.value.find(c => c.id === bindingForm.value.camera_id)
    bindingForm.value.camera_name = camera ? camera.name : ''
    
    // 准备保存的数据
    const bindingData = {
      camera_id: bindingForm.value.camera_id,
      camera_name: bindingForm.value.camera_name,
      algorithms: bindingForm.value.algorithms.map(alg => ({
        algorithm_id: alg.algorithm_id,
        algorithm_name: alg.algorithm_name,
        service_id: alg.service_id,
        algorithm_type: alg.algorithm_type,
        enabled: alg.enabled,
        priority: alg.priority,
        config: {
          confidence_threshold: alg.config.confidence_threshold,
          detection_interval: alg.config.detection_interval,
          max_detections: alg.config.max_detections || 10
        }
      }))
    }
    
    console.log('保存绑定数据:', bindingData)
    
    try {
      if (editingBinding.value) {
        const response = await aiAlgorithmApi.updateCameraBinding(bindingForm.value.camera_id, bindingData)
        if (response.code === 200) {
          ElMessage.success('更新成功')
        } else {
          throw new Error(response.msg || '更新失败')
        }
      } else {
        const response = await aiAlgorithmApi.createCameraBinding(bindingData)
        if (response.code === 200) {
          ElMessage.success('创建成功')
        } else {
          throw new Error(response.msg || '创建失败')
        }
      }
      
      showBindingDialog.value = false
      await loadBindings()
      
    } catch (apiError) {
      console.error('API调用失败:', apiError)
      
      // 如果API调用失败，在本地模拟保存
      ElMessage.warning('后端服务暂不可用，数据已保存到本地缓存')
      
      if (editingBinding.value) {
        // 更新现有绑定
        const index = bindings.value.findIndex(b => b.camera_id === bindingForm.value.camera_id)
        if (index !== -1) {
          bindings.value[index] = {
            ...bindingData,
            id: editingBinding.value.id,
            created_at: editingBinding.value.created_at,
            updated_at: new Date().toISOString()
          }
        }
      } else {
        // 添加新绑定
        bindings.value.push({
          ...bindingData,
          id: `binding_${Date.now()}`,
          created_at: new Date().toISOString(),
          updated_at: new Date().toISOString()
        })
      }
      
      showBindingDialog.value = false
    }
    
  } catch (err) {
    console.error('保存绑定失败:', err)
    ElMessage.error(editingBinding.value ? '更新失败' : '创建失败')
  } finally {
    saving.value = false
  }
}

// 重置表单
const resetBindingForm = () => {
  editingBinding.value = null
  bindingForm.value = {
    camera_id: '',
    camera_name: '',
    algorithms: []
  }
  activeServiceTab.value = 'campus_behavior_monitoring'
  if (bindingFormRef.value) {
    bindingFormRef.value.resetFields()
  }
}

// 格式化时间
const formatDateTime = (dateStr) => {
  return new Date(dateStr).toLocaleString()
}



// 生命周期
onMounted(async () => {
  console.log('=== 摄像头算法绑定组件初始化 ===')
  
  // 首先加载摄像头数据
  try {
    await cameraStore.fetchCameras()
    console.log('✅ 摄像头数据已加载:', cameraStore.cameras.length, '个摄像头')
  } catch (error) {
    console.error('❌ 加载摄像头数据失败:', error)
    ElMessage.error('加载摄像头数据失败')
  }
  
  // 加载绑定数据
  console.log('🔄 开始加载绑定数据...')
  await loadBindings()
  console.log('✅ 绑定数据已加载:', bindings.value.length, '个绑定')
  
  // 输出六大AI服务信息
  console.log('📋 六大AI服务及30个算法:')
  Object.entries(AI_SERVICES_WITH_ALGORITHMS).forEach(([serviceId, serviceInfo]) => {
    console.log(`  - ${serviceInfo.name} (${serviceId}):`)
    Object.entries(serviceInfo.algorithms).forEach(([algType, algName]) => {
      console.log(`    * ${algName} (${algType})`)
    })
  })
  
  // 检查API连接状态
  console.log('🔗 检查Python后端API连接状态...')
  try {
    const response = await fetch('/python-api/health')
    if (response.ok) {
      const data = await response.json()
      console.log('✅ Python后端API连接正常:', data)
    } else {
      console.warn('⚠️ Python后端API响应异常:', response.status)
    }
  } catch (error) {
    console.error('❌ Python后端API连接失败:', error)
    ElMessage.warning('Python后端服务未启动，请启动AI算法API服务')
  }
})
</script>

<style lang="scss" scoped>
.camera-algorithm-binding {
  padding: 20px;
  
  .binding-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h3 {
      margin: 0;
      font-size: 18px;
      font-weight: 600;
      color: #303133;
    }
    
    .header-actions {
      display: flex;
      gap: 12px;
    }
  }
  
  .binding-stats {
    margin-bottom: 20px;
    
    .stat-card {
      padding: 20px;
      background: #fff;
      border-radius: 8px;
      text-align: center;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
      border-left: 4px solid #409eff;
      transition: transform 0.3s ease;
      
      &:hover {
        transform: translateY(-2px);
      }
      
      .stat-number {
        font-size: 28px;
        font-weight: bold;
        color: #303133;
        margin-bottom: 8px;
      }
      
      .stat-label {
        font-size: 14px;
        color: #606266;
      }
    }
  }
  
  .bindings-list {
    .camera-info {
      display: flex;
      align-items: center;
      gap: 8px;
    }
    
    .algorithms-list {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
      
      .algorithm-tag {
        display: flex;
        align-items: center;
        gap: 4px;
        
        .priority {
          font-size: 10px;
          opacity: 0.8;
        }
      }
    }
  }
  
  .services-selection {
    .service-algorithms {
      .service-description {
        margin-bottom: 20px;
        padding: 16px;
        background: #f8f9fa;
        border-radius: 6px;
        
        p {
          margin: 0;
          color: #606266;
          font-size: 14px;
          line-height: 1.5;
        }
      }
      
      .algorithms-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
        gap: 16px;
        
        .algorithm-option {
          cursor: pointer;
          transition: all 0.3s ease;
          
          &:hover {
            transform: translateY(-2px);
          }
          
          &.selected {
            .algorithm-card {
              border-color: #409eff;
              box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
            }
          }
          
          &.enabled {
            .algorithm-card {
              border-color: #67c23a;
            }
          }
          
          .algorithm-card {
            border: 2px solid #e4e7ed;
            border-radius: 8px;
            padding: 16px;
            background: #fff;
            height: 100%;
            transition: all 0.3s ease;
            
            .algorithm-header {
              display: flex;
              align-items: center;
              gap: 12px;
              margin-bottom: 12px;
              
              h4 {
                margin: 0;
                font-size: 16px;
                font-weight: 600;
                color: #303133;
                flex: 1;
              }
            }
            
            .algorithm-info {
              margin-bottom: 16px;
              
              .algorithm-id {
                font-size: 12px;
                color: #909399;
                margin: 0 0 8px 0;
                font-family: monospace;
              }
              
              .algorithm-desc {
                font-size: 14px;
                color: #606266;
                margin: 0;
                line-height: 1.4;
              }
            }
            
            .algorithm-config {
              .el-form-item {
                margin-bottom: 12px;
              }
            }
          }
        }
      }
    }
  }
  
  .selected-summary {
    margin-top: 20px;
    
    .summary-list {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
    }
  }
  
  .dialog-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .footer-info {
      font-size: 14px;
      color: #606266;
    }
    
    .footer-actions {
      display: flex;
      gap: 12px;
    }
  }
}

.dark .camera-algorithm-binding {
  .binding-header {
    h3 {
      color: #e4e7ed;
    }
  }
  
  .binding-stats {
    .stat-card {
      background: #2d2d2d;
      
      .stat-number {
        color: #e4e7ed;
      }
      
      .stat-label {
        color: #909399;
      }
    }
  }
  
  .services-selection {
    .service-algorithms {
      .service-description {
        background: #2d2d2d;
        
        p {
          color: #909399;
        }
      }
      
      .algorithms-grid {
        .algorithm-option {
          .algorithm-card {
            background: #2d2d2d;
            border-color: #4c4d4f;
            
            .algorithm-header h4 {
              color: #e4e7ed;
            }
            
            .algorithm-info {
              .algorithm-id {
                color: #909399;
              }
              
              .algorithm-desc {
                color: #909399;
              }
            }
          }
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .camera-algorithm-binding {
    padding: 16px;
    
    .services-selection {
      .service-algorithms {
        .algorithms-grid {
          grid-template-columns: 1fr;
        }
      }
    }
  }
}
</style>